package com.ffzx.commerce.framework.exception;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.alibaba.fastjson.JSON;
import com.ffzx.commerce.framework.constant.Constant;
import com.ffzx.commerce.framework.utils.StackTraceToString;
import com.ffzx.commerce.framework.utils.UUIDGenerator;
import com.ffzx.commerce.framework.vo.ResultVo;

/**
 * MySimpleExceptionResolver
 * 
 * @author CMM
 *
 * 2016年8月9日 下午4:47:42
 */
public class MySimpleExceptionResolver extends SimpleMappingExceptionResolver {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }
	
	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		//错误唯一标识，为了异常日志的跟踪
		String errorCode = UUIDGenerator.getUUID();
		String errorMassage = ex.getMessage();
		String errorStackTrace = StackTraceToString.getStackTrace(ex);
		
		//输出异常信息
		logger.error("errorCode:" + errorCode);
		logger.error("错误信息:", ex);
		
		//ajax请求
		if ((request.getHeader("accept").indexOf("application/json") > -1 || (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
			ResultVo resultVo = new ResultVo();
			resultVo.setStatus(Constant.RESULT_ERR);
			resultVo.setInfoStr(Constant.RESULT_ERR_MSG);
			resultVo.setInfoError("errorCode:" + errorCode + "\n errorMassage:" + errorMassage + "\n errorStackTrace:" + errorStackTrace);
			
			String message = JSON.toJSONString(resultVo);
			
			response.reset();
			response.setContentType(Constant.RESPONSE_CONTENT_TYPE);
			
			try {
	        	response.getWriter().print(message);
	        	response.getWriter().flush();
	        } catch (IllegalStateException ise) {  // If getOutputStream() has already been called
	        	try {
					response.getOutputStream().print(message);
					response.getOutputStream().flush();
				} catch (IOException ioe) {
					logger.error("异常处理错误(GenericHandlerExceptionResolver):", ioe);
				}
	        } catch (IOException ioe) {
	        	logger.error("异常处理错误(GenericHandlerExceptionResolver):", ioe);
			}
			
			return null;
		}else {
			Map<String, Object> model = new HashMap<String, Object>();
			model.put("errorCode", errorCode);
			model.put("errorMassage", errorMassage);
			model.put("errorStackTrace", errorStackTrace);
			
			// 根据不同的异常类型做对应的处理
			if (ex instanceof ServiceException) {
				return new ModelAndView("error/500", model);
			} else {
				return new ModelAndView("error/500", model);
			}
		}
	}

}
